const { Result } = require("../util/result");
const express = require('express');
const router = express.Router();
const db = require('../util/db');
const {qPromise} = require("../util/qPromise");



/*todo-搜索for管理*/
router.get('/searchForAdmin', async (req, res) => {

    let str=''
    let str2=''
    if(req.query.cid!=0){
        str='and cid = '+req.query.cid
        str2='and cid = '+req.query.cid
    }
    let limit=10
    if(req.query.pageSize!=null)limit=req.query.pageSize
    let offset=0
    if(req.query.currentPage!=null)offset=(req.query.currentPage-1)*limit
    let sql=`select article.id,cid,name,title,description,visitTimes,article.createTime from article,category where cid=category.id ${str} LIMIT ${limit} OFFSET ${offset};`
    let sql2=`select count(*) as total from article,category where cid=category.id ${str2}`

    try {
        const [data, total] = await Promise.all([
            qPromise(sql,[]),
            qPromise(sql2, [])
        ]);

        res.json(new Result(200,'查询成功', {data: data, total: total[0].total}));
    } catch (error) {
        console.error(error);
        res.status(500).json(new Result(500,'查询失败', null));
    }
});

router.put('/update', (req, res) => {
    let sql=`update article set title=?,description=?,main=?,cid=? where id=?`
    db.query(sql, [req.body.title,req.body.description,req.body.main,req.body.cid,req.body.id], (data) => {
        if (data.affectedRows === 1)
            res.json( new Result(200, '修改成功', null))
        else res.json( new Result(500, '修改失败', null))
    })
})



module.exports= router;